/**
 * 
 */
package org.agiba.jira.plugin.persistence;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.agiba.jira.plugin.model.XWikiInstance;

import com.opensymphony.module.propertyset.PropertySet;
import com.opensymphony.module.propertyset.PropertySetManager;
import com.thoughtworks.xstream.XStream;

/**
 * @author kamtho
 *
 */
public class ConfigurationHandler {
	private static PropertySet ps = null;
	private static XStream xstream;
	
	private long entityId;
	private String entityName;
	private String dataVersion;
	
	@SuppressWarnings("unused")
	private ConfigurationHandler(){}
	
	public ConfigurationHandler(long entityid, String entityName, String dataVersion){
		this.entityId = entityid;
		this.entityName = entityName;
		this.dataVersion = dataVersion;
		
		xstream = new XStream();
		xstream.alias("xwiki-instance", XWikiInstance.class);
	}
	
	@SuppressWarnings("unchecked")
	private PropertySet getPS(){
		if (ps == null){
			@SuppressWarnings("rawtypes")
			Map psArgs = new HashMap();
            psArgs.put("delegator.name", "default");
            psArgs.put("entityName", entityName);
            psArgs.put("entityId", new Long(entityId));
            // See propertyset.xml for choices of types here
            ps = PropertySetManager.getInstance("ofbiz", psArgs);
		}
		return ps;
	}
	
	public void saveXWikiInstance(XWikiInstance instance){
		XStream xstream = new XStream();
		xstream.alias("xwiki-instance", XWikiInstance.class);		
		getPS().setText(instance.getKey(), xstream.toXML(instance));
	}
	
	@SuppressWarnings("unchecked")
	public List<String> loadInstanceKeys(){
		return (List<String>) getPS().getKeys();
	}
	
	public XWikiInstance loadXWikiInstance(String instanceKey){
		String result;
		
		result = getPS().getText(instanceKey);
		XWikiInstance instance = (XWikiInstance) xstream.fromXML(result);
		instance.setKey(instanceKey);
		return instance;
	}
	
	public void removeInstance(XWikiInstance instance){
		getPS().remove(instance.getKey());
	}
	
}
